package com.xjtucrafter.kiwi.account.dao.impl;

import com.xjtucrafter.kiwi.account.bean.Account;
import com.xjtucrafter.kiwi.account.dao.AccountDao;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * User: Dash
 * Date: 4/21/16 Time: 9:10 PM
 */
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao{

    @PersistenceContext(name="unitName")
    private EntityManager entityManager;

    @Override
    public int accountAdd(Account account) {
        entityManager.persist(account);
        return account.getAccountID();
    }

    @Override
    public Account accountQuery(String accountPhone) {
        String jpql = "select account from Account account where account.accountPhone=:phone";
        Account account = (Account) entityManager.createQuery(jpql)
                .setParameter("phone", accountPhone)
                .getSingleResult();
        return account;
    }

    @Override
    public int accountUpdate(Account account) {
        String jpql = "update Account acount set " +
                "acount.accountName=:name," +
                "acount.accountPassword=:password," +
                "acount.accountAvatar=:avatar where acount.accountPhone=:phone";
        int result = entityManager.createQuery(jpql)
                .setParameter("name", account.getAccountName())
                .setParameter("password",account.getAccountPassword())
                .setParameter("avatar", account.getAccountAvatar())
                .setParameter("phone", account.getAccountPhone())
                .executeUpdate();
        return result;
    }

    @Override
    public int accountDelete(String accountPhone) {
        String jpql = "delete from Account account where account.accountPhone=:phone";
        int result = entityManager.createQuery(jpql)
                .setParameter("phone", accountPhone)
                .executeUpdate();
        return result;
    }
}
